#include "base/timeevent.h"
#include "base/timer.h"
#include "base/timebplustree.h"
#include "base/timequeue.h"
#include "base/log.h"
namespace net_tools::base{
Timequeue::Timequeue()
  :timer_(new Timer()),
   timerfd_(timer_->Gettimefd()),
   time_out_read_buf(),
   timebplustree_(new Timebplustree())
{
  gettimeofday(&min_timeval_,NULL);
  min_sec_ = min_timeval_.tv_sec;
  min_usec_ = min_timeval_.tv_usec;
};
void Timequeue::Addtimeevent(Timeevent* p_timeevent){
  p_timeevent->Add_set();
  timebplustree_->Insert_timeevent(p_timeevent);
  Resettimer();
};
void Timequeue::Timeout(){
  read(timerfd_,time_out_read_buf,sizeof(uint64_t));
  timebplustree_->Dotimeevent();
  Resettimer();
};
void Timequeue::Resettimer(){
  if(timebplustree_->Is_empty()){
    return;
  }
  min_timeval_ = timebplustree_->Get_min_time();
  timeval now_,set_;
  gettimeofday(&now_,NULL);
  set_.tv_usec = min_timeval_.tv_usec - now_.tv_usec;
  set_.tv_sec = min_timeval_.tv_sec - now_.tv_sec;
  if(set_.tv_usec < 0){
    set_.tv_usec += 1000000;
    --set_.tv_sec;
  }
  if(set_.tv_sec < 0){
    set_.tv_usec = 0;
    set_.tv_sec = 0;
  }
  timer_->Settime(set_);
};

} // namespace net_tools::base